// src/config/database.ts
import mongoose from 'mongoose'
import { config } from './index'

const connectDB = async (): Promise<void> => {
  try {
    const conn = await mongoose.connect(config.database.url, {
      serverSelectionTimeoutMS: 10000, // 服务器选择超时时间
      socketTimeoutMS: 45000, // Socket超时时间
      connectTimeoutMS: 10000 // 连接超时时间
    })

    console.log(`MongoDB 连接成功: ${conn.connection.host}`)
  } catch (error) {
    console.error('数据库连接失败:', error)
    process.exit(1)
  }
}

// 监听连接事件
mongoose.connection.on('error', (err: Error) => {
  console.error('数据库连接失败:', err)
})

mongoose.connection.once('open', () => {
  console.log('数据库连接成功')
})

mongoose.connection.on('disconnected', () => {
  console.log('数据库连接断开')
})

// 监听重启信号，优雅关闭连接
process.on('SIGINT', async () => {
  await mongoose.connection.close()
  console.log('数据库连接已关闭')
  process.exit(0)
})

export default connectDB
